package request

import (
	"QImages/global"
	"errors"
	"github.com/imroc/req"
	"io"
)

// ImageServiceConfig 图片服务的配置信息
type ImageServiceConfig struct {
	Url       string
	AppKey    string
	AppSecret string
}

// Result 上传图片之后的响应信息
type Result struct {
	Url       string `json:"url"`
	Code      int    `json:"code"`
	Timestamp string `json:"timestamp"`
	Message   string `json:"message"`
}

// PostImage 上传图片
func PostImage(fileName string, file io.ReadCloser) (string, error) {
	res, err := req.Post(global.Config.ImageService.Url, req.FileUpload{
		File:      file,
		FieldName: "image",
		FileName:  fileName,
	}, req.Param{
		"app_key":    global.Config.ImageService.AppKey,
		"app_secret": global.Config.ImageService.AppSecret,
	})
	if err != nil {
		return "", err
	}
	var r Result
	err = res.ToJSON(&r)
	if err != nil {
		return "", err
	}
	if r.Code == 2000 {
		return r.Url, nil
	} else {
		return "", errors.New(r.Message)
	}
}
